package com.chixigua.chaos.utils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class CustomExceptionUtils {
    public static void throwCustomException(HttpServletResponse response, JSONObject jsonObject){
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        ObjectMapper objectMapper = new ObjectMapper();
        String resBody = null;
        PrintWriter printWriter = null;
        try {
            resBody = objectMapper.writeValueAsString(jsonObject);
            printWriter = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        printWriter.print(resBody);
        printWriter.flush();
        printWriter.close();
    }
}
